package com.eschool.beans.converter;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import com.eschool.dao.SchoolDao;
import com.eschool.model.School;

public class SchoolConverter implements Converter {

	public static List<School> schoolDB;

	public SchoolConverter() {
		schoolDB = new ArrayList<School>();
		schoolDB = SchoolDao.getSchools(null);
	}

	@Override
	public Object getAsObject(FacesContext facesContext, UIComponent component,
			String submittedValue) {
		// TODO Auto-generated method stub
		if (submittedValue.trim().equals("")) {
			return null;
		} else {
			try {
				for (School s : schoolDB) {
					if (s.getSchoolName().equalsIgnoreCase(submittedValue)) {
						return s;
					}
				}

			} catch (NumberFormatException exception) {
				throw new ConverterException(new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Conversion Error",
						"Not a Valid School"));
			}
		}
		return null;
	}

	@Override
	public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
		// TODO Auto-generated method stub
		if (value == null || value.equals("")) {
			return "";
		} else {
			return ((School) value).getSchoolName();
		}
	}

}
